<template>
	<view class="grace-body">
		<fu-custom bgColor="bg-white" :isBack="true" :isBottom="true">
			<block slot="content">{{i18n['我的资料']}}</block>
		</fu-custom>
		<!-- 个人资料表单 start -->
		<form @submit="formSubmit" class="grace-form grace-margin-top">
			<!-- 顶部头像模块 start -->
			<!-- TODO: 点击保存后再保存头像，而非上传完成 -->
			<view class="head_list cu-list menu">
				<view class="cu-item">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">店铺logo</text>
						<view class="demo-face grace-relative grace-img-in">
							<!-- @tap="openImg()" -->
							<image :src="storeInfo.store_logo || '/static/logo.png'" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
			<!-- 顶部头像模块 end -->
			<view class="cu-list menu ">
				<view class="cu-item">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">店铺名称</text>
						<text class=" text-lg text-666 text-right">{{storeInfo.store_name}}</text>
					</view>
				</view>
				<!-- 昵称 start -->
				<view class="cu-item ">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">经营分类</text>
						<text class=" text-lg text-666 text-right">{{storeInfo.store_introduce}}</text>
						<!-- <input type="text"  :selection-start="user_name.length" :selection-end="user_name.length"
              :cursor="user_name.length" class="input text-lg text-666" name="user_nickname" maxlength="10"
              :auto-blur="true" v-model="user_nickname" :placeholder="i18n['请输入昵称']" style="text-align: right" /> -->
					</view>
				</view>
				<!-- 昵称 end -->

				<!-- 性别 start -->
				<view class="cu-item">
					<view class="content flex justify-between align-center">
						<text class="title text-lg text-333">店铺所在地</text>
						<view class="text-666 text-right ">{{storeInfo.store_province_name}}-{{storeInfo.store_city_name}}-{{storeInfo.store_district_name}}</view>
					</view>
				</view>
				<!-- 性别 end -->
				<view class="padding-lr bg-white ">
					<view class=" flex  flex-direction solid-bottom  padding-tb">
						<text class=" text-lg text-333">详细地址</text>
						<text class="text-333 margin-top-sm">{{storeInfo.store_address}}</text>
					</view>
				</view>
				<view class="padding-lr bg-white">
					<view class="flex  align-center justify-between solid-bottom  padding-tb">
						<text class=" text-lg text-333">店铺客服电话</text>
						<text class="text-666">{{storeInfo.service_phone}}</text>
					</view>
				</view>
				<view class="padding-lr bg-white ">
					<view class=" flex  flex-direction   padding-tb">
						<text class=" text-lg text-333">店铺背景 <text class="text-red text-sm">（可修改）</text></text>
						<view class="margin-top-sm">
							<image :src="storeInfo.store_backdrop || '/static/logo.png'" mode="aspectFill" @tap="chooseImg()"
								class="width-268  height-170"></image>
						</view>
					</view>
				</view>
				<!-- 所在地 start -->
				<!-- <view class="cu-item">
          <view class="content flex justify-between align-center">
            <text class="title text-lg text-333 address">{{i18n['所在地']}}</text>
            <view class="text-lg text-666 text-cut-2 text-align-right" @tap="toggleTab('region')">
              <view :class="name == i18n['点击选择'] ? '' : 'address-select'">{{
                name
                }}</view>
            </view>
          </view>
        </view> -->
				<!-- 所在地 end -->
			</view>
		</form>
		<!-- 个人资料表单 end -->
	
		<!-- 头像start -->
		<fu-popup v-model="headerShow" borderRadius="16" :safeAreaInsetBottom="true" mode="bottom">
			<view class="header-popup text-333 text-weight-400 text-lg text-center">
				<!-- <view class="header-100" @click="chooseImage(0)">
					{{i18n['修改头像']}}
				</view> -->
				<view class="header-100 solid-top" @click="chooseImage(1)">
					{{i18n['拍照']}}
				</view>
				<view class="header-100 solid-top" @click="chooseImage(2)">
					{{i18n['从手机相册选择']}}
				</view>
				<view class="height-20"></view>
				<view class="header-100 text-red" @click="headerShow = false">
					{{i18n['取消']}}
				</view>
			</view>
		</fu-popup>
		<!-- 头像end -->
		<!-- <view class="footer">
			<button class="bottom-action text-theme" @click="saveUserInfo()">{{i18n['保存']}}</button>
		</view> -->
		<!-- 断网检测 start -->
		<fu-notwork></fu-notwork>
		<!-- 断网检测 end -->
	</view>
</template>

<script>
	// @see 引入组件wPicker
	import wPicker from "../../components/w-picker/w-picker.vue";
	// @see 引入验证，上传图片
	import {
		UploadImage,
		validate
	} from "@/common/utils/index";
	// @let {?Fuction} timer - 保存定时器
	let timer = null;
	export default {
		components: {
			wPicker,
		},
		data() {
			return {
				isLoading: false, // {Boolean} 是否加载中
				storeInfo: {}, // {Objcet} 用户信息			
				thumb: global.SYSTEM_CONFIG.logo, // {String} 默认图片				
			
				timeVisible: false, //时间组件
				visible: false, //性别组件
				headerShow: false,
			};
		},
		computed: {
			sexName() {
				let name = this.sex[this.sexIndex].name;
				console.log('this.sexIndex', name);
				return name;
			},
			themeColor() {
				return this.$store.state.themeColor;
			}
		},
		watch: {
			user_nickname(val) {
				console.log(val, this.form.user_nickname, this.form.user_nickname == val);
				if (val != this.form.user_nickname) {
					this.isCanSave = true;
				}
			},	
		
		},
		onLoad(option) {
		this.getStoreInfo()
		/**
		 * @description 监听监听上传头像事件
		 */
		uni.$on("uPicCropper", (path) => {
			this.uploadUserImg(path);
		});
	
	},
	onUnload() {
			// 关闭当前页面的监听事件
			uni.$off("uPicCropper");
			uni.$off("changeMobile");
		},
		
		methods: {
			getStoreInfo(){
				this.$api.post('/v1/6356316a22bb0', {
						partner_id: (global.userInfo && global.userInfo.id) || 0, //店铺id
						user_id: (global.userInfo && global.userInfo.id) || 0
					}).then(res => {
					let data = res.data.data;
					this.storeInfo = data					
				
				}).catch(err => {
					this.$message.info("服务器错误，请稍后重试");
				});
			},
			/**
			 * @description 页面返回
			 * @param {delta} delta = 返回的页面数，如果 delta 大于现有页面数，则返回到首页
			 */
			back(delta) {
				if (this.isCanSave) {
					this.$util.showModal({
						title: this.i18n["提示"],
						content: this.i18n["你有修改未保存，是否确认保存"] + '?',
						success: (res) => {
							if (res.confirm) {
								this.saveUserInfo();
								uni.hideKeyboard();
							} else if (res.cancel) {
								uni.navigateBack();
							}
						},
					});
					return false;
				}
				console.log("页面返回");
				uni.navigateBack({
					delta: delta || 1,
				});
			},
			/**
			 * @event
			 * @description 所在地的选择弹窗显示
			 */
			toggleTab(ref) {
				this.$refs[ref].show();
			},
			// 保存用户信息
			saveUserInfo() {

				// 校验
				// 如果不为空的情况下使用验证方法去验证邮箱号
				if (this.user_email) {
					if (!validate(this.user_email, "email")) {
						this.$message.info(this.i18n["请输入正确的邮箱账号"]);
						return;
					}
				}


				if (!this.user_nickname.trim()) {
					this.$message.info(this.i18n["请输入昵称"]);
					return;
				}

				let data = {
					user_nickname: this.user_nickname,
					sex: this.sexIndex,
					user_email: this.user_email,
					birthday: this.dateValue,
					address: this.name,
					address_code: this.defaultVal,
				};
				this.$util.throttle(() => {
					this.upload(data);
				}, 2000)
			},
			/**
			 * @event
			 * @description 表单上传事件
			 * @param {Object} val - 用户单独保存某一项时传进来的参数
			 */
			upload(val) {
				this.$api.post(global.apiUrls.editUserinfo, val).then((res) => {
					if (res.data.code == 1) {
						// 更新本地缓存
						uni.setStorageSync("USER_INFO", res.data.data.userinfo);
						// 更新用户信息
						this.userInfo = Object.assign({}, uni.getStorageSync("USER_INFO"));
						// 更新global的用户信息
						global.userInfo = res.data.data.userinfo;
						uni.showToast({
							title: res.data.msg,
							duration: 1000,
							icon: "none",
						});
						// 保存旧数据
						this.form.user_nickname = this.user_nickname;
						this.form.user_email = this.user_email;
						this.form.sexIndex = this.sexIndex;
						this.form.dateValue = this.dateValue;
						this.form.defaultVal = this.defaultVal;
						// 更新保存状态
						this.isCanSave = false;
						setTimeout(() => {
							uni.navigateBack();
						}, 500);
					} else {
						this.$message.info(res.data.msg);
					}
				});
			},
			/**
			 * @event
			 * @description 保存用户姓名事件
			 */
			saveUsername() {
				if (
					this.userInfo.user_name == this.user_name ||
					this.user_name == "" ||
					this.user_name.length > 10
				)
					return;
				// this.upload({ user_name: this.user_name });
			},
			/**
			 * @event
			 * @description 性别选择事件
			 */
			bindPickerChange: function(e) {
				this.sexIndex = e.detail.value;
				if (this.userInfo.sex == this.sexIndex) return;
				// this.upload({ sex: this.sexIndex });
			},
			/**
			 * @description 选择性别
			 */
			chooseSex() {
				let that = this;
				uni.showActionSheet({
					itemList: that.sex,
					success: function(res) {
						console.log(["选中了第"] + (res.tapIndex + 1) + ["个按钮"]);
						that.sexIndex = res.tapIndex;
						if (that.userInfo.sex == that.sexIndex) return;
						// that.upload({ sex: that.sexIndex });
					},
					fail: function(res) {
						console.log(res.errMsg);
					},
				});
			},
			/**
			 * @event
			 * @description 生日选择事件
			 * @param {!Object} e - 用户生日弹窗选择的值
			 */
			bindDateChange: function(e) {
				let selectTime = new Date(e.detail.value);
				let nowTime = new Date();
				if (selectTime > nowTime) {
					this.$message.info(this.i18n["请选择正确的时间"]);
					return;
				}
				this.dateValue = e.detail.value;
				if (this.userInfo.birthday == this.dateValue || !this.dateValue) return;
				// this.upload({ birthday: this.dateValue });
			},

			/**
			 * @event
			 * @description 所在地选择事件
			 * @param {Object} result - 用户所在地弹窗选择的值
			 */
			onConfirm(result, type) {
				console.log(result, type);
				if (type == 'date') {
					this.dateValue = result.value;
				}
				if (type == 'region') {
					let {
						province,
						city,
						area
					} = result.obj;
					let text = [province.label, city.label, area.label];
					let code = [province.value, city.value, area.value];
					this.name = text.join("-");
					this.city1 = text;
					this.defaultVal = code;
					if (this.userInfo.address_code == this.defaultVal || this.userInfo.address == this.name) return;
				}
				if (type == 'selector') {
					this.sexIndex = result.value;
				}
				// this.upload({
				//   address: this.name,
				//   address_code: this.defaultVal,
				// });
			},
			openImg() {
				this.headerShow = true;
			},
			chooseImg() {
				this.headerShow = true;
			},
			/**
			 * @event
			 * @description 选择头像事件
			 */
			chooseImage(tapIndex) {
				let that = this;
				if (tapIndex == 0) {
					let img = that.head_img || that.thumb;
					uni.navigateTo({
						url: '/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=' +
							img,
						animationDuration: 0,
					});
				} else if (tapIndex == 1) {
					uni.chooseImage({
						count: 1,
						sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
						success: (res) => {
							this.uploadUserImg(res.tempFilePaths[0])
							// 跳转到图片裁切页面
							// uni.navigateTo({
							// 	url: '/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=' +
							// 		res.tempFilePaths[0],
							// 	animationDuration: 0,
							// });
						},
					});
				} else {
					uni.chooseImage({
						count: 1,
						sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有
						success: (res) => {
							this.uploadUserImg(res.tempFilePaths[0])
							// 跳转到图片裁切页面
							// uni.navigateTo({
							// 	url: `/pages/user/user/avatar-cropping/index?rectHeight=200&rectWidth=200&fileType=jpg&myImgUrl=${res.tempFilePaths[0]}`,
							// 	animationDuration: 0,
							// });
						},
					});
				}
				this.headerShow = false;
			},
			// 表单提交
			formSubmit: function(e) {
				if (this.isLoading) return;

				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout(() => {
					var formData = e.detail.value;

					// 添加头像
					formData.head_img = this.head_img;

					// 处理生日字段
					formData.birthday =
						formData.birthday.indexOf(this.i18n["选择"]) != -1 ? "" : formData.birthday;

					// 所在地
					formData.address = this.name.indexOf(this.i18n["选择"]) != -1 ? "" : this.name;
					formData.address_code = this.defaultVal;

					// 添加用户ID
					formData.user_id = this.userInfo.id ? this.userInfo.id : "";

					// 进行表单验证操作
					let validateRes = this.doValidate(formData);
					if (validateRes) {
						this.$message.info(validateRes);
						return;
					}
					console.log('birthday', formData.birthday);

					this.isLoading = true;
					this.$api
						.post(global.apiUrls.editUserinfo, formData)
						.then((res) => {
							// setTimeout(() => {
							//   this.isLoading = false;
							// }, 500)
							if (res.data.code == 1) {
								this.isLoading = false;
								// 更新本地缓存
								uni.setStorageSync("USER_INFO", res.data.data.userinfo);

								// 更新global
								global.userInfo = res.data.data.userinfo;
								this.$message.info(this.i18n["修改成功"]);
								setTimeout(() => {
									uni.navigateBack();
								}, 500);
							}
						})
						.catch((err) => {
							this.isLoading = false;
							console.log(err);
						});
				}, 300);
			},

			// 进行表单字段值校验
			doValidate(formData) {
				console.log(formData);

				// 昵称
				if (!formData.user_nickname) {
					return this.i18n["请输入您的用户昵称"];
				}

				if (formData.user_nickname.length > 10) {
					return this.i18n["请检查您的昵称(最多10个字符)"];
				}

				// 生日
				if (!formData.birthday) {
					return this.i18n["请选择您的生日"];
				}

				return "";
			},

			/**
			 * @description 上传用户头像
			 */
			uploadUserImg(blob) {
				uni.showLoading();
				let _this = this;
				// 开始上传
				new UploadImage([blob], {
					complete: function(res) {
						uni.hideLoading();
						if (res.length) {
							// _this.head_img = res[0].path;
							var formData = {
								head_img: res[0].id,
							};
							_this.storeInfo.store_backdrop=  res[0].path
							_this.$api
								.post(global.apiUrls.editUserinfo, formData)
								.then((res) => {
									if (res.data.code == 1) {
										
										// 更新本地缓存
										// uni.setStorageSync("USER_INFO", res.data.data.userinfo);
										// 更新global
										// global.userInfo = res.data.data.userinfo;
									}
								});
						}
					},
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.cu-list.menu {
		margin-top: 0;
	}

	.demo text {
		margin: 10upx;
	}

	.demo-face {
		width: 100rpx;
		height: 100rpx;
	}

	.demo-face image {
		width: 100rpx;
		height: 100rpx;
		border-radius: 60rpx;
	}

	.picker {
		background: #00b26a;
		width: 100%;
		line-height: 40px;
	}

	.head_list {
		background: #fff;
		padding: 20rpx 0;
		height: 152rpx;
		position: relative;

		&::after {
			content: "";
			position: absolute;
			bottom: 0;
			left: 32rpx;
			width: 100%;
			height: 1px;
			background: #ddd;
			transform: scaleY(0.5);
		}
	}

	.other {
		width: 500rpx;
		text-align: right;
	}

	.address {
		display: inline-block;
		width: 110rpx;
	}

	.cu-item.arrow::before {
		color: #bfbfbf !important;
	}

	.cu-list.menu>.cu-item {
		// height: 110rpx;
	}

	.address-select {
		// display: inline-block;
		width: 400rpx;
		// overflow: hidden;
		// white-space: nowrap;
		// text-overflow: ellipsis;
	}

	.content .title {
		display: inline-block;
		width: 160rpx;
		min-width: 160rpx;
	}

	.text-align-right {
		text-align: right;
	}

	.footer {
		position: fixed;
		left: 0rpx;
		bottom: 0rpx;
		width: 100%;
		height: 110rpx;
		height: calc(110rpx + constant(safe-area-inset-bottom));
		height: calc(110rpx + env(safe-area-inset-bottom));
		background: #FFFFFF;

		.bottom-action {
			height: 110rpx;
			line-height: 110rpx;
			background: #FFFFFF;
			padding: 0;
			border-radius: 0;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FF6464;

			&::after {
				border: 0;
				border-radius: 0;
			}
		}
	}

	.cu-list.menu-avatar>.cu-item:after,
	.cu-list.menu>.cu-item:after {
		left: 32rpx;
	}

	.header-popup {
		.height-20 {
			height: 20rpx;
			background: #f8f8f8;
		}

		.header-100 {
			height: 100rpx;
			line-height: 100rpx;
		}
	}

	/deep/ .sex-wrap .w-picker-view {
		height: 228rpx;
	}

	/deep/ .birthday-wrap uni-picker-view .uni-picker-view-wrapper {
		padding: 0 80rpx;
	}
</style>
